package com.itCar.base.api.wxApi.wxAuth.util;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.*;

/**
 * @ClassName: Utils
 * @Description: TODO 调用图灵机器人 实现智能对话
 * @author: liuzg
 * @Date: 2022/9/1 9:58
 * @Week: 星期四
 * @Version: v1.0
 */
@Slf4j
public class Utils {

    //此处为图灵机器人key
    public static final String API_KEY = "1702c05fc1b94e2bb4de7fb2e61b21a3";

    //存储接口请求地址
    public static final String API_URL = "http://www.tuling123.com/openapi/api";

    private static final String APPID = "wx148e4e32f56a200e";
    private static final String APPSECRET = "4a1ebdbfaec3aee2cf1f6931b4630662";
    private static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET + "";

    /*
    A 对 B 说：你是谁啊
    B 对 A 说：那不说了..
    A 对 B 说：秘密是天机不可泄露的。
    B 对 A 说：不可说那就不说呗。
    A 对 B 说：偏要说！
    B 对 A 说：你别说了
     */
    public static void main(String[] args) {
        boolean flag = true;
        int count = 0;
        Utils tuling = new Utils();
        String firstSentence = "你好";
        String message = "";
        System.out.println("A 对 B 说：" + firstSentence);
        message = tuling.getMessage(firstSentence);
        do {
            String man = "";
            if (isOdd(count)){
                man = "B 对 A 说：";
            }else {
                man = "A 对 B 说：";
            }
            System.out.println(man + message);
            message = tuling.getMessage(message);
            count++;
//            if (count > 10){ // 每天10次请求机会
            if ("亲爱的，当天请求次数已用完。".equals(message)){
                count = 0;
                flag = false;
            }
        } while (flag);


        System.out.println(message);
    }

    public static boolean isOdd(int a){
        if((a&1) != 1){   //是奇数
            return true;
        }
        return false;
    }

    /**
     * 提供对外公开的方法用于最终拿到机器人回复的消息
     *
     * @param msg 传入你需要发送的信息
     * @return 机器人对你的回复
     */
    public String getMessage(String msg) {
        return getString(getHTML(setParameter(msg)));
    }

    private String setParameter(String msg) {
        //在接口请求中 中文要用URLEncoder encode成UTF-8
        try {
            return API_URL + "?key=" + API_KEY + "&info=" + URLEncoder.encode(msg, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getString(String json) {
        try {
            JSONObject object = JSONObject.parseObject(json);
            return object.getString("text");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;

    }

    private String getHTML(String url) {
        StringBuffer buffer = new StringBuffer();
        BufferedReader bufferedReader = null;
        try {
            //创建URL对象
            URL u = new URL(url);
            //打开连接
            HttpURLConnection connection = (HttpURLConnection) u.openConnection();
            //从连接中拿到InputStream并由BufferedReader进行读取
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            //循环每次加入一行HTML内容 直到最后一行
            while ((line = bufferedReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //结束时候关闭释放资源
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer.toString();
    }


    /**
     * 自定义请求 向指定地址发送get请求
     *
     * @param url 参数请求地址
     * @return
     */
    public static String get(String url) {
        try {
            URL u = new URL(url);
            // 开链接
            URLConnection connection = u.openConnection();
            InputStream stream = connection.getInputStream();
            byte[] b = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = stream.read(b)) != -1) {
                sb.append(new String(b, 0, len));
            }
            return sb.toString();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 自定义请求 向指定地址发送post请求 带着data数据
     *
     * @param url 参数请求地址
     * @return
     */
    public static String post(String url, String data) {
        OutputStream os = null;
        try {
            URL u = new URL(url);
            // 开链接
            URLConnection connection = u.openConnection();
            // 要发送数据出去， 必须要设置为可发送数据状态
            connection.setDoOutput(true);
            os = connection.getOutputStream();
            // 写出数据
            os.write(data.getBytes());
            // 获取输入流
            InputStream is = connection.getInputStream();
            byte[] b = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = is.read(b)) != -1) {
                sb.append(new String(b, 0, len));
            }
            return sb.toString();
        } catch (Exception e) {
            log.error(e.getMessage());
        }finally {
            if (os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
        return null;
    }

}
